// UserRolePermissionPage.tsx
import React, { useState } from 'react';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import { useNavigate } from 'react-router-dom'; 
import {
  Box, Typography, Grid, Button, Table, TableBody, TableCell, TableHead, TableRow,
  Paper, List, ListItem, ListItemText, Checkbox, Divider, Stack
} from '@mui/material';
import { createTheme, ThemeProvider, CssBaseline } from "@mui/material";
import UserDialog from '../components/UserDialog';
import AddRoleDialog from '../components/AddRoleDialog';
import theme from "../themes/theme2"

const rolePermissions: Record<string, string[]> = {
  '系统管理员': ['行业模型库管理', '评估模型维护', '数据采集配置', '智能评估生成', '专家评估管理', '重点工程与项目管理'],
  '评估管理员': ['评估模型维护', '智能评估生成'],
  '数据分析师': ['数据采集配置', '智能评估生成'],
  '评估专员': ['专家评估管理'],
};

const allRoles = Object.keys(rolePermissions);

const UserRolePermissionPage: React.FC = () => {
  
  const [showUserForm, setShowUserForm] = useState(false);
  const [editingUser, setEditingUser] = useState<any>(null);
    const [users, setUsers] = useState([
  { id: 1, userId: 'admin001', name: '张三', department: 'IT部门', role: '系统管理员' },
  { id: 2, userId: 'user002', name: '李四', department: '财务部', role: '数据分析师' },
  { id: 3, userId: 'user003', name: '王五', department: '销售部', role: '评估专员' },
]);

  //roles
  const [showAddRoleDialog, setShowAddRoleDialog] = useState(false);
  const [roles, setRoles] = useState<string[]>(Object.keys(rolePermissions));
  const [rolePermissionsMap, setRolePermissionsMap] = useState<Record<string, string[]>>(rolePermissions);
  const [selectedRole, setSelectedRole] = useState<string>('系统管理员');
  const [checkedPermissions, setCheckedPermissions] = useState<string[]>(rolePermissions[selectedRole]);



  const navigate = useNavigate();

  const handleRoleSelect = (role: string) => {
  setSelectedRole(role);
  setCheckedPermissions(rolePermissionsMap[role] || []);
};

 const handlePermissionToggle = (perm: string) => {
  const updated = checkedPermissions.includes(perm)
    ? checkedPermissions.filter(p => p !== perm)
    : [...checkedPermissions, perm];

  setCheckedPermissions(updated);

  setRolePermissionsMap(prev => ({
    ...prev,
    [selectedRole]: updated
  }));
};
    const handleCreateUser = (user: any) => {
          console.log('提交新用户:', user);
          // 自动生成一个新的 id（实际项目应由后端返回）
          const newUser = {
            ...user,
            id: users.length ? users[users.length - 1].id + 1 : 1
        };
        
        setUsers(prev => [...prev, newUser]);
        // 可调用 API 提交表单数据
        setShowUserForm(false);
    };

    const handleCancelCreateUser = () => {
      setShowUserForm(false);
    };

const handleUserSubmit = (user: any) => {
  if (user.id) {
    // 编辑模式
    setUsers(prev =>
      prev.map(u => (u.id === user.id ? { ...u, ...user } : u))
    );
  } else {
    // 创建模式
    const newUser = {
      ...user,
      id: users.length ? users[users.length - 1].id + 1 : 1,
    };
    setUsers(prev => [...prev, newUser]);
  }
};



    //***UI part */
  return (
<ThemeProvider theme={theme}>
         <CssBaseline />
    <Button
      variant="outlined"
      onClick={() => navigate("/")}
      sx={{ mb: 2 }}
    >
      ← 返回
    </Button>

    <Box sx={{ display: 'flex', minHeight: '100vh', background: '#0A1929', p: 4 }}>
   

      {/* 左侧：用户管理 */}
      <Paper sx={{ flex: 1, mr: 2, backgroundColor: '#102840', p: 3, borderRadius: 3 }}>
        <Typography variant="h6" sx={{ color: '#fff', mb: 2 }}>
          👥 用户管理
        </Typography>

        <Table sx={{ backgroundColor: '#173A5E', borderRadius: 2 }}>
          <TableHead>
            <TableRow>
              {['#', '用户ID', '姓名', '所属部门', '角色', '操作'].map((col, index) => (
                <TableCell key={index} sx={{ color: '#90CAF9' }}>{col}</TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
              {users.map(user => (
                <TableRow key={user.id}>
                  <TableCell sx={{ color: '#fff' }}>{user.id}</TableCell>
                  <TableCell sx={{ color: '#fff' }}>{user.userId}</TableCell>
                  <TableCell sx={{ color: '#fff' }}>{user.name}</TableCell>
                  <TableCell sx={{ color: '#fff' }}>{user.department}</TableCell>
                  <TableCell sx={{ color: '#fff' }}>{user.role}</TableCell>
                  <TableCell>
                    <Stack direction="row" spacing={1}>
                      <Button variant="contained" size="small" sx={{ backgroundColor: '#2962FF' }}  onClick={() => setEditingUser(user)}>
                        编辑
                      </Button>
                      <Button variant="contained" size="small" sx={{ backgroundColor: '#D32F2F' }}>
                        禁用
                      </Button>
                    </Stack>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
        </Table>

        <Box mt={2} display="flex" justifyContent="space-between">
          <Stack direction="row" spacing={2}>
            <Button variant="contained" sx={{ backgroundColor: '#2E7D32' }} onClick={() => setEditingUser({})}>+ 添加用户</Button>
            <Button variant="contained" sx={{ backgroundColor: '#2962FF' }}>📤 导入</Button>
          </Stack>
          <Typography variant="body2" sx={{ color: '#90CAF9' }}>
            显示 1-3 / 共 24 条
          </Typography>
        </Box>
      </Paper>

      {/* 右侧：角色与权限配置 */}
      <Paper sx={{ flex: 1, backgroundColor: '#102840', p: 3, borderRadius: 3 }}>
        <Typography variant="h6" sx={{ color: '#fff', mb: 2 }}>
          🛡️ 角色与权限分配
        </Typography>

        <Grid container spacing={2}>
          <Grid item xs={4}>
            <Typography sx={{ color: '#90CAF9', mb: 1 }}>角色列表</Typography>
            <List sx={{ backgroundColor: '#173A5E', borderRadius: 1 }}>
              {roles.map(role => (
                <ListItem
                  key={role}
                  button
                  selected={role === selectedRole}
                  onClick={() => handleRoleSelect(role)}
                  sx={{
                    color: '#fff',
                    '&.Mui-selected': {
                      backgroundColor: '#2962FF',
                      '&:hover': { backgroundColor: '#2962FFaa' }
                    }
                  }}
                >
                  <ListItemText primary={role} />
                </ListItem>
              ))}
            </List>
            <Button
              fullWidth
              variant="contained"
              sx={{ mt: 2, backgroundColor: '#2E7D32' }}
              onClick={() => setShowAddRoleDialog(true)}
            
            >
              + 新增角色
            </Button>
            {/**user dialog to CRUD user status*/}
            <UserDialog
              open={!!editingUser}
              user={editingUser}
              onClose={() => setEditingUser(null)}
              onSubmit={handleUserSubmit}
            />
            <AddRoleDialog
            open={showAddRoleDialog}
            allPermissions={Array.from(new Set(Object.values(rolePermissionsMap).flat()))}
            onClose={() => setShowAddRoleDialog(false)}
             onSubmit={(roleName, permissions) => {
              if (!roles.includes(roleName)) {
                // 1. 添加角色
                setRoles(prev => [...prev, roleName]);

                // 2. 设置权限映射
                setRolePermissionsMap(prev => ({
                  ...prev,
                  [roleName]: permissions
                }));

                // ✅ 3. 立即选中该角色
                setSelectedRole(roleName);

                // ✅ 4. 更新右侧 checkbox 状态
                setCheckedPermissions(permissions);
              }

              setShowAddRoleDialog(false);
            }}
          />
          </Grid>

          <Grid item xs={8}>
            <Typography sx={{ color: '#90CAF9', mb: 1 }}>
              权限配置（{selectedRole}）
            </Typography>
            <Paper sx={{ p: 2, backgroundColor: '#173A5E', borderRadius: 2 }}>
              <Box display="flex" flexDirection="column" gap={1}>
                {Array.from(new Set(Object.values(rolePermissions).flat())).map(perm => (
                  <Box key={perm} display="flex" alignItems="center">
                    <Checkbox
                      checked={checkedPermissions.includes(perm)}
                      onChange={() => handlePermissionToggle(perm)}
                      sx={{ color: '#90CAF9' }}
                    />
                    <Typography sx={{ color: '#fff' }}>{perm}</Typography>
                  </Box>
                ))}
              </Box>

              <Divider sx={{ my: 2, borderColor: '#90CAF9' }} />
              <Stack direction="row" spacing={2}>
                <Button variant="contained" sx={{ backgroundColor: '#616161' }}>取消</Button>
                <Button variant="contained" sx={{ backgroundColor: '#2962FF' }}>保存配置</Button>
              </Stack>
            </Paper>
          </Grid>
        </Grid>
      </Paper>
      </Box>
  </ThemeProvider>  
  );

};

export default UserRolePermissionPage;
